<?php

namespace App\Kuafu\Mybank\Controller\Internal;

use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Mybank\Model\MybankEntryModel;
use App\Kuafu\Mybank\Service\MybankBrokerageService;
use App\Kuafu\Mybank\Service\MybankEntryService;
use App\Kuafu\Mybank\Service\MybankOrderWithholdV2Service;
use App\Kuafu\Mybank\Service\MybankService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class MybankController extends BaseController
{
    /**
     * 获取抽佣配置
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getBrokerageConfig(Request $request)
    {
        $key = $request->get('key', 'default');

        $list = MybankBrokerageService::getMybankBrokerage($key);
        return $this->success($list);
    }

    /**
     * 网商余额查询
     * @param Request $request
     */
    public function balance(Request $request)
    {
        $userId = $request->get('userId');

        $this->validate($request, [
            'userId' => 'required|integer|min:1',
        ]);

        $model = (new MybankOrderWithholdV2Service())->setMerchantIdByUserId($userId);

        $data['PAY'] = $model->getBalancePay();

        return $this->success($data);
    }

    /**
     * 网商账号注册状态
     * @param Request $request
     */
    public function registerStatus(Request $request)
    {
        $userId = $request->get('userId');

        $this->validate($request, [
            'userId' => 'required|integer|min:1',
        ]);

        return $this->success(MybankEntryService::registerStatus($userId));
    }

    /**
     * 网商账户状态和余额
     * @param Request $request
     * @return JsonResponse
     * @throws GuzzleException
     * @throws ValidationException
     */
    public function accountDetail(Request $request): JsonResponse
    {
        $userId = $request->get('userId');
        $this->validate($request, [
            'userId' => 'required|integer|min:1',
        ]);
        $data = MybankEntryService::registerStatus($userId);

        $data['balance'] = 0;
        if ($data['status'] == MybankEntryModel::STATUS_3) {
            $data['balance'] = (new MybankOrderWithholdV2Service())->setMerchantIdByUserId($userId)->getBalancePay();
        }
        return $this->success($data);
    }
}
